package rs.networx.servlets;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import rs.networx.dao.NottificationDao;
import rs.networx.dao.PersonDao;
import rs.networx.dao.PostDao;
import rs.networx.entity.Nottification;
import rs.networx.entity.Person;
import rs.networx.entity.Post;
import rs.networx.util.PropertiesUtil;

public class AddPictureServlet extends HttpServlet {

	private static final long serialVersionUID = -1436384713064350773L;

	@EJB
	private PersonDao personDao;
	
	@EJB
	private NottificationDao nottificationDao;
	
	@EJB
	private PostDao postDao; 

	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;

	private String postTitlePicture;
	private String postTextPicture;

	private BufferedImage imageFromPost;
	private String imageNameFromPost;

	private String imageExtensionFromPost;
	private String imageNameForDBFromPost;
	
	private String propertyFile;
	private String networxDir;
	
	private Post picturePost;
	
	private Set<Person> loggedUsersFriendsSet;
	private List<Person> loggedUsersFriendsList;
	
	private List<Post> loggedUsersOwnedPosts;
	
	private Integer nottificationsCount;
	
	private boolean isMultipart;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		System.out.println("*** Loaded PostPictureOnLoggedUserWallServlet ***");

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());

		HttpSession session = request.getSession();
		loggedUser = (Person)session.getAttribute("logovaniUser");

		try {	
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();
			System.out.println(username + "  " + password + "  " + intLoggedUserID);
		} catch (Exception e) {
			//e.printStackTrace();
		}

		if(loggedUser != null){
			try {
				// Check that we have a file upload request...
				isMultipart = ServletFileUpload.isMultipartContent(request);

				if(isMultipart){
					// Create a factory for disk-based file items...
					FileItemFactory factory = new DiskFileItemFactory();

					// Create a new file upload handler...
					ServletFileUpload upload = new ServletFileUpload(factory);

					// Parse the request...
					List<FileItem> items = upload.parseRequest(request);

					// getting all fields from form...
					for(FileItem fileItem : items){
						// if a form field...
						if(fileItem.isFormField()){
							if(fileItem.getFieldName().equals("postTitlePicture")){							
								postTitlePicture = fileItem.getString();
								System.out.println("postTitlePicture: " + postTitlePicture);
								continue;
							}
							if(fileItem.getFieldName().equals("postTextPicture")){							
								postTextPicture = fileItem.getString();
								System.out.println("postTextPicture: " + postTextPicture);
								continue;
							}
						}
						// if picture...
						if(!fileItem.isFormField()){
							imageFromPost = ImageIO.read(fileItem.getInputStream());
							imageNameFromPost = fileItem.getName();
							System.out.println("imageName: " + imageNameFromPost);						
						}
					}
				}

				// creating new post...
				picturePost = new Post();
				picturePost.setTitle(postTitlePicture);
				picturePost.setText(postTextPicture);
				picturePost.setType(1);
				picturePost.setDate(Calendar.getInstance().getTime());

				// only temporary saving empty picture name...
				picturePost.setContent("");

				picturePost.setPoster(loggedUser);
				picturePost.setOwner(loggedUser);

				// saving to generate the ID...
				postDao.persist(picturePost);

				imageExtensionFromPost = imageNameFromPost.substring(imageNameFromPost.lastIndexOf('.') + 1);
				imageNameForDBFromPost = picturePost.getId() + "." + imageExtensionFromPost;

				// setting image name and merging...
				picturePost.setContent(imageNameForDBFromPost);
				picturePost = postDao.merge(picturePost);
				System.out.println("New post: " + picturePost);

				// saving image in full size...
				propertyFile = getServletContext().getRealPath("networx.properties");
				networxDir = PropertiesUtil.getProperty(propertyFile, "networxDir");
				ImageIO.write(imageFromPost, imageExtensionFromPost, new File(networxDir + "/imagePost/" + imageNameForDBFromPost));
					
				// treba jos dodati i notifikaciju da je dati loggedd user okacio novi post...
				// adding nottification to logged user...
				Nottification nottification = new Nottification();
				nottification.setOwner(loggedUser);
				nottification.setTargetID(picturePost.getId());
				nottification.setType(2);
				nottification.setViewed(false);
				nottification.setLink("You Added New Picture " + 
									  "<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
						  			  " To Your Wall.");	
				nottificationDao.persist(nottification);
				
				// sada bi trebalo dodati i po notifikaciju za svakog prijatelja logged usera da je logged user okacio novi post...
				loggedUsersFriendsSet = personDao.getFriends(intLoggedUserID);
				System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
				
				if(loggedUsersFriendsSet == null || loggedUsersFriendsSet.size() == 0){
					// znaci da nema prijatelja, pa idemo dalje...
					System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
					
				}else if(loggedUsersFriendsSet != null && loggedUsersFriendsSet.size() > 0){
					loggedUsersFriendsList = new ArrayList<Person>();
					
					Iterator<Person> iter = loggedUsersFriendsSet.iterator();
				    while(iter.hasNext()){
				    	loggedUsersFriendsList.add((Person)iter.next());
				    }
				    System.out.println("loggedUsersFriendsList: " + loggedUsersFriendsList.size());
				    
				    // sada treba za svakog prijatelja da napravimo po notifikaciju...
					for(int i = 0; i < loggedUsersFriendsList.size(); i++){
						// adding nottification to logged users friends...
						Nottification nottification2 = new Nottification();
						nottification2.setOwner(loggedUsersFriendsList.get(i));
						nottification2.setTargetID(picturePost.getId());
						nottification2.setType(2);
						nottification2.setViewed(false);
						nottification2.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
		   			  			  			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
		   			  			  			   " Added New Picture " + 
		   			  			  			   "<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
		   			  			  			   " To " + 
		   			  			  			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
		   			  			  			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + "'s" + 
		   			  			  			   " Wall.");	
						nottificationDao.persist(nottification2);
					}
				}
				
				// dobavljamo 10 postova za logovanog korisnika...
				loggedUsersOwnedPosts = personDao.getFirstTenOwnedPosts(loggedUser.getId());
				System.out.println("loggedUsersOwnedPosts: " + loggedUsersOwnedPosts.size());
				
				// sada dobavljamo i notifikacije za datog ulogovanog korisnika ako ih ima...
				nottificationsCount = nottificationDao.getNottificationsCountForLoggedUser(loggedUser);
				System.out.println("nottificationsCount: " + nottificationsCount);
				
				session.setAttribute("loggedUsersOwnedPosts", loggedUsersOwnedPosts);
				session.setAttribute("nottificationsCount", nottificationsCount);
				
				response.sendRedirect("ViewWallServlet");
				return;
			}catch (FileUploadException e){
				//e.printStackTrace();
				
				// obrada ako dodje do greske prilikom uploada slike...
				request.getRequestDispatcher("UploadPictureError.jsp").forward(request, response);
				return;
			}
		}else if(loggedUser == null){
			request.getRequestDispatcher("Welcome.jsp").forward(request, response);
			return;
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}


}
